from django.db import models
import uuid
from django.utils import timezone

from apps.UserManagement.models import User


class Questions(models.Model):
    class Meta:
        db_table = 'questions'

    objects = models.Manager
    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    # 试题标题
    topic = models.TextField(max_length=500, help_text='试题标题')
    # 试题选项
    options = models.TextField(max_length=500, null=True, blank=True, help_text='试题选项')
    # 试题答案
    answer = models.CharField(max_length=500, null=True, blank=True, help_text='试题参考答案')
    # 简答答案（关键字）
    keywords = models.CharField(max_length=500, null=True, blank=True, help_text='简答答案（关键字）')
    # 试题类型
    TYPE_CHOICES = [
        ('single', 'Single'),
        ('multiple', 'Multiple'),
        ('judge', 'Judge'),
        ('short', 'Short'),
    ]
    type = models.CharField(max_length=10, choices=TYPE_CHOICES, default='single',
                            help_text='试题类型：单选（single），多选（multiple），判断（judge），简答（short）')
    # 考试类别
    classify = models.CharField(max_length=500, null=True, blank=True, help_text='考试类别')
    # 难易程度
    DIFFICULTY_CHOICES = [
        ('easy', 'easy'),
        ('medium', 'Medium'),
        ('hard', 'hard'),
    ]
    difficulty = models.CharField(max_length=20, choices=DIFFICULTY_CHOICES, default='easy',
                                  help_text='试题难度：简单（easy），中等（medium），困难（hard）')
    # 创建人（外键）
    created_user = models.ForeignKey(User, related_name='created_questions', on_delete=models.SET_NULL, null=True,
                                     blank=True)
    # 创建时间
    created_at = models.DateTimeField(default=timezone.now, help_text='创建时间')
    # 更新人（外键）
    updated_user = models.ForeignKey(User, related_name='updated_questions', on_delete=models.SET_NULL, null=True,
                                     blank=True)
    # 更新时间
    updated_at = models.DateTimeField(auto_now=True, null=True, help_text='更新时间')

    def get_options(self):
        return self.options.split(';') if self.options else []

    def set_options(self, options_list):
        self.options = ';'.join(options_list)

    def get_answer(self):
        if self.type == 'judge':
            # 判断题，返回字符串 '0' 或 '1'，表示 False 或 True
            return self.answer  # '0' 或 '1'
        else:
            # 非判断题，返回分号分隔的选项下标字符串
            return self.answer if self.answer else ''

    def set_answer(self, answer_list):
        if self.type == 'judge':
            # 判断题，将布尔值转换为字符串 '0' 或 '1'（0表示False，1表示True）
            self.answer = '1' if answer_list[0] else '0'
        else:
            # 非判断题，存储为分号分隔的选项下标（如 '0;1;2'）
            self.answer = ';'.join(map(str, answer_list))

    def get_keywords(self):
        return self.keywords.split(';') if self.keywords else []

    def set_keywords(self, keywords_list):
        self.keywords = ';'.join(keywords_list)

    def get_classify(self):
        return self.classify.split(';') if self.classify else []

    def set_classify(self, classify_list):
        self.classify = ';'.join(classify_list)

    def __str__(self):
        return self.topic

    def save(self, *args, **kwargs):
        # 处理answer字段的存储方式
        if self.type == 'judge' and isinstance(self.answer, str):
            # 判断题的答案应存储为选项的下标，'true' 对应 0, 'false' 对应 1
            if self.answer == 'true':
                self.answer = '0'
            elif self.answer == 'false':
                self.answer = '1'
        elif isinstance(self.answer, list):
            self.answer = ';'.join(map(str, self.answer))
        super().save(*args, **kwargs)

